import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import AnimatedTransition from '../AnimatedTransition';
import api from '../axios/index';
import './styleCss/Home.scss';
import CommonPullToRefresh from '../compages/CommonPullToRefresh';
import CategoryCarousel from '../compages/CategoryCarousel';
import LocationBar from '../compages/LocationBar';

// 添加商品接口类型
interface Product {
    id: number;
    title: string;
    price: number;
    images: string[];
    context: string;
}

interface AuthState {
    isAuthenticated: boolean | string;
}

interface RootState {
    auth: AuthState;
}

const Home = () => {
    const navigate = useNavigate();
    // 添加商品列表状态
    const [products, fetchProducts] = useState<Product[]>([]);
    // 分类数据示例
    const categories = [
        { icon: '图片1地址', label: '新鲜水果' },
        { icon: '图片2地址', label: '鸡鸭鱼肉' },
        { icon: '图片3地址', label: '产地蔬菜' },
        { icon: '图片1地址', label: '新鲜水果' },
        { icon: '图片2地址', label: '鸡鸭鱼肉' },
        { icon: '图片3地址', label: '产地蔬菜' },
        { icon: '图片1地址', label: '新鲜水果' },
        { icon: '图片2地址', label: '鸡鸭鱼肉' },
        { icon: '图片3地址', label: '产地蔬菜' },
        { icon: '图片1地址', label: '新鲜水果' },
        { icon: '图片2地址', label: '鸡鸭鱼肉' },
        { icon: '图片3地址', label: '产地蔬菜' },
        { icon: '图片1地址', label: '新鲜水果' },
        { icon: '图片2地址', label: '鸡鸭鱼肉' },
        { icon: '图片3地址', label: '产地蔬菜' },
    ];

    // 假设你的 redux 里有 isAuthenticated 字段
    const isAuthenticated = useSelector((state: RootState) => state.auth.isAuthenticated);

    // 获取商品数据的函数
    const fetchPro = async () => {
        try {
            const response = await api.get('/all-products');
            fetchProducts(response.data.data);
        } catch (error) {
            console.error('获取商品失败: ', error);
        }
    }

    // 组件挂载时获取商品数据
    useEffect(() => {
        fetchPro();
    }, []);

    // 动画结束后在判断跳转
    const handleDetailClick = (product: Product) => {
        if (!isAuthenticated === true || isAuthenticated === true) {
            // 已登录，跳转到 purchase 页面 并通过 state 传递商品数据
            navigate('/purchase', { replace: true, state: { product } });
        } else {
            // 未登录，跳转到登录页
            navigate('/', { replace: true });
        }
    }

    return (
        <AnimatedTransition>
            <CommonPullToRefresh onRefresh={(async () => {
                // 这里可以加2秒延迟模拟
                await new Promise(res => setTimeout(res, 2000));
                await fetchPro();
            })}>
                {/* 搜索框容器 */}
                <div className="home-search-bar">
                    {/* 搜索图标 */}
                    <span className="search-icon">🔍</span>
                    {/* 输入框，placeholder 可自定义 */}
                    <input
                        className="search-input"
                        type="text"
                        placeholder="墨西哥牛油果【限时限量】"
                    // onChange={...} // 这里可以绑定搜索逻辑
                    />
                    {/* 相机图标 */}
                    <span className="camera-icon">📷</span>
                </div>
                <LocationBar/>
                <CategoryCarousel categories={categories}/>
                <div className="home-title">推荐热门</div>
                <div>
                    {
                        <div className="products-grid">
                            {
                                products.map(product => {
                                    return (
                                        <div key={product.id} className="product-card">
                                            <img src={product.images[0]} alt={product.title} className='product-image' />
                                            <div className="product-info" onClick={() => handleDetailClick(product)}>
                                                <h4>{product.title}</h4>
                                                <p>￥{product.price}</p>
                                            </div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    }
                </div>
            </CommonPullToRefresh>
        </AnimatedTransition>
    )
}

export default Home;